<?php

defined('BASEPATH') or die('forbidden');

class Api_Controller Extends Controller {
	private $tmpconnect;
    private $data = array();
    private $logParamVal = 20;

    function _init() {

		include  'area/ActivityCfg.php';
//        header("Content-Type: application/json; charset=utf-8");
//        $result = $this->input->deep_stripslashes($_POST);
//        if ($result['sig'] == get_sig($result)) {
//            $this->data = isset($result['data']) ? get_json_array($result['data']) : array();
//            $method = str_replace("/", "_", $result['url']);
//            if (method_exists($this, "_" . $method)) {
//                $this->{"_{$method}"}();
//            }
//        } else {
//            json_output(0, '签名错误');
//        }
        $this->inc = $this->config['inc'];
        $this->wholeServerHost = $this->config['host_url'];
    }

    function get_app_configpath($app) {
        $name = '/application/configs/config.php';
        if ($app != 'application') {
            $name = '/' . $app . $name;
        }
        return ROOTPATH . $name;
    }

    //分区请求注册
    function register_area() {
        $row = array();
        $id = $row['id'] = $_REQUEST['id'];
        $row['host'] = $_REQUEST['host'];
        $row['name'] = $_REQUEST['name'];
        $connectFlag = $_REQUEST['connectFlag'];    //1表示是全局服务器来注册

        if ($connectFlag == '1') {
            include CONFIGPATH . 'config.php';
            $config['host_url'] = $row['host'];
            ob_start();
            echo "<?php \ndefined('BASEPATH') or die('forbidden');\n\$config = " . array2val($config) . ";";
            $content = ob_get_contents();
            ob_clean();
            @file_put_contents($this->get_app_configpath('application'), $content);
            exit;
        }


        $row['lastopentime'] = time();

        $one = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$id}'");

        $paymentDb = $this->load->database('payment_db');

        $register_res = true;
        if (count($one) >= 1) {
            $row['resettimes'] = $one['resettimes'] + 1;
            $register_res = $this->db->update("{pre}areasample", $row, array('id' => $row['id']));
            echo "update";
            //做服务器注册日志
        } else {
            $row['resettimes'] = 1;
            $row['state'] = '4';      //默认是测试状态
            $register_res = $this->db->insert("{pre}areasample", $row);
            echo "insert";
            //做服务器注册日志
        }

        //支付数据库也要更新
        $one2 = $paymentDb->one("SELECT * FROM {pre}areasample WHERE id='{$id}'");
        if (count($one2) >= 1) {
            $register_res2 = $paymentDb->update("{pre}areasample", $row, array('id' => $row['id']));
        } else {
            $register_res2 = $paymentDb->insert("{pre}areasample", $row);
        }
//        $rowdata['id'] = (int) $row['id'];
//        $rowdata['opentime'] = (int) $row['opentime'];
//        $rowdata['state'] = (int) $row['state'];
//        $rowdata['flag'] = (int) $row['flag'];
//        $rows[] = $rowdata;
//        $list['arealist'] = $rows;
//        $jsonStr = json_encode($list);
//        $result = vpost($this->wholeServerHost . "areas=$jsonStr&action=47");

        if ($register_res === false || $register_res2 === false) {
            log_message("register server fail");
            echo "fail";
        }

        $one = $this->db->one("SELECT * FROM {pre}area_current WHERE id='{$id}'");
        if (count($one) < 1) {
            $now = date("Y-m-d H:i:s", time());
            $sql = "INSERT INTO {pre}area_current(id,name,currentonline,maxonline,registercount,updatetime) VALUES({$id},'null',0,0,0,'{$now}')";
            $res = $this->db->execute($sql);
            if ($res == FALSE)
                log_message("server current data insert fail");
        }
    }

    //服务器关闭时请求
    function unregister_area() {
//        $id = $_REQUEST['id'];
//        $one = $this->db->one("SELECT * FROM {pre}areasample WHERE id='{$id}'");
//        if (is_array($one)) {
//            $this->db->query("UPDATE {pre}areasample SET state='2' WHERE id='{$id}'");
//            //做服务器注销日志
//            echo "success";
//        }
    }

    function onGameServerDown() {
        $subject = $_REQUEST["subject"];
        $body = $_REQUEST["body"];
        $this->sendemail("13319404811@139.com", $subject, date("Y-m-d H:i:s") . " " . $body);
        $this->sendemail("13979118908@139.com", $subject, date("Y-m-d H:i:s") . " " . $body);
        //$this->sendemail("18679106423@139.com", $subject, $body);
        //echo "success";
    }

    function sendemail($smtpemailto, $mailsubject, $mailbody) {
        require_once(APPPATH . '\libraries\email.class.php');
        $smtpserver = "smtp.qq.com"; //SMTP服务器
        $smtpserverport = '25'; //SMTP服务器端口

        $smtpemailto = $smtpemailto; //发送给谁

        $smtpusermail = "895827676@qq.com"; //SMTP服务器的用户邮箱
        $smtppass = "mbx13006298842.0"; //SMTP服务器的用户密码

        $mailsubject = $mailsubject; //邮件主题
        $mailbody = $mailbody; //邮件内容
        $mailtype = "HTML"; //邮件格式（HTML/TXT）,TXT为文本邮件
        ##########################################
        $smtp = new smtp($smtpserver, $smtpserverport, true, $smtpusermail, $smtppass); //这里面的一个true是表示使用身份验证,否则不使用身份验证.
        $smtp->debug = false; //是否显示发送的调试信息
        $smtp->sendmail($smtpemailto, $smtpusermail, $mailsubject, $mailbody, $mailtype);
    }

    //实时数据刷新
    function areaOnlineData() {

    	$this->db->query("SELECT * FROM {pre}area_current");
    	while ($row = $this->db->get_array()) {
    		$tmprows[$row['id']] = $row['updatetime'];  //变动之前的updatetime
    	}

        $getrow = $_GET;
        $getrow["updatetime"] = date("Y-m-d H:i:s", time());
        //print_r($row);
        $res = $this->db->update("{pre}area_current", $getrow, array('id' => $getrow['id']));
        if ($res == FALSE)
            log_message("area current data update fail");
        else
            echo "success";
        
        /*********服务器宕机数据tt_businessserver***add by dragon.hu @ 2016.1.5*******/
        /*$this->db->query("SELECT * FROM {pre}area_current");
        while ($row = $this->db->get_array()) {
        	$rows[$row['id']] = $row;
        }
        //var_dump($rows);
        $sql = "SELECT * FROM tt_businessserver";
        $this->db->query($sql);
        while ($row = $this->db->get_array())
        {
        	$busrows[$row['area']][$row['downtime']] = $row;
        }
        //var_dump($busrows);
        //检查宕机的服务器是否已重新启动，以此算出宕机时长
        foreach ($rows as $key => $value)
        {
        	$tmparrinfo = get_area_list_option();
        	$rowdata['area'] = $tmparrinfo[$value['id']];
        	//var_dump($value['id']);
        	//var_dump($tmparrinfo);
        	//var_dump($tmparrinfo[$value['id']]);
        	$sql = "SELECT opentime FROM tt_areasample WHERE id = ".$value['id'];
        	$one = $this->db->one($sql);
        	$rowdata['begintime'] = date("Y-m-d H-i-s", $one['opentime']);
        	if(time() - strtotime($value['updatetime']) > 30)
        	{
        		if (empty($busrows[$rowdata['area']][$value['updatetime']]))
        		{
        			$rowdata['downtime'] = $value['updatetime'];
        			$rowdata['durationtime'] = "service outages";
        			$rowdata['addtime'] = date("Y-m-d H-i-s", time());
        			$result = $this->db->insert ( 'tt_businessserver', $rowdata);
        		}
        	}
        	else
        	{
        		if (isset($busrows[$rowdata['area']][$tmprows[$value['id']]]))
        		{
        			$tmptime = round((time() - strtotime($busrows[$rowdata['area']][$tmprows[$value['id']]]['downtime'])) / 60, 2);
        			$sql = "UPDATE tt_businessserver SET durationtime = '". $tmptime .
        			 " 分钟' WHERE area ='".$rowdata['area']."' and downtime = '".$tmprows[$value['id']]."'";
        			$this->db->execute($sql);
        		}
        		else
        		{
        			//两次心跳间隔的时间
        			if (strtotime($value['updatetime']) - strtotime($tmprows[$value['id']]) > 30)  //只有一个服务器发心跳，停掉再到有心跳的情况
        			{
        				$rowdata['downtime'] = $tmprows[$value['id']];
        				$rowdata['durationtime'] = round((strtotime($value['updatetime']) - strtotime($tmprows[$value['id']])) / 60, 2);
        				$rowdata['durationtime'] .= " 分钟";
        				$rowdata['addtime'] = date("Y-m-d H-i-s", time());
        				$result = $this->db->insert('tt_businessserver', $rowdata);
        			}
        		}
        	}
        }*/
        /**************************************************************************/
        
        //2015.10.22需求@dragon.hu add 当某台服务器的人数到了一个稳定值后，自动修改下一个服务器的状态(如果下一个也是良好，则以此类推)
        $config = get_config();
        
        #$this->log("areaOnlineDataLog", "maxonline=" . $config['maxonline'] . "   currentonline=" . $getrow["currentonline"]);
        if ($config['maxonline'] != 0)//为0时表示关闭
        {
        	if ($getrow["currentonline"] >= $config['maxonline'])
        	{
        		//修改相邻的下一个分区的状态(如果为测试就改为良好) select * from table where id>$id order by id asc limit 1;
        		$sql = "select * from tt_areasample where id >" . $getrow['id'] . " order by CAST(id as SIGNED) asc limit 1";
                #$this->log("areaOnlineDataLog", "sql=" . $sql);

        		$one = $this->db->one($sql);
        		if ($one == NULL)
        		{
                    $tmp = 1;
        			log_message("select next area failed ");
        		}
        		else
        		{
        			if ($one['state'] == 4)//只能由测试状态到良好状态
        			{
						$act_cfg = new ActivityCfg();
						$act_cfg->updateStartTime($one['id'], time(), $one['host'], true);
						
        				$one['state'] = 0;  //改为良好
                        $one['opentime'] = time();  //修改开服时间
						
        				$tmp_rows[] = $one;
        				$list['arealist'] = $tmp_rows;
        				$jsonStr = json_encode($list);
        				$result = vpost($this->wholeServerHost."areas=$jsonStr&action=47");
        				$ret = $this->db->update("tt_areasample", $one, array('id' => $one['id']));

        				if ($ret == FALSE)
						{
        					log_message("areasample data update fail ");
							#echo("fail   " . time());
						}
						else
						{
							#echo(time());
						}
        			}
        		}
        	}
        }
    }

    //服务器更新回调
    function areaUpdateReturn() {
        $row = $_GET;
        $row["insert_time"] = date("Y-m-d H:i:s", time());
        $one = $this->db->one("SELECT * FROM {pre}area_update_log WHERE areaid='" . $row['areaid'] . "' AND `version`='" . $row['version'] . "'");
        if (count($one) < 1) {
            $this->db->insert("{pre}area_update_log", $row);
            if ($res == FALSE) {
                log_message("server update operate info insert fail");
            } else {
                echo "success";
            }
        } else {
            $sql = "INSERT INTO {pre}area_update_log set strResult='" . $row['strResult'] . ",`insert_time`='" . $row['insert_time'] . "' WHERE areaid='" . $row['areaid'] . "' AND `version`='" . $row['version'] . "'";
            //$this->db->update("{pre}area_update_log",$row,array())
            $res = $this->db->execute($sql);
            if ($res == FALSE) {
                log_message("server update operate info update fail");
            } else {
                echo "success";
            }
        }
    }

    function AppStoreCheckOrder() {
        $orderid = $_REQUEST['orderid'];
        $serverid = $_REQUEST['serverid'];
        $roleid = $_REQUEST['roleid'];          //请求校验的角色ID
        $accountid = $_REQUEST['accountid'];
        $channel = $_REQUEST['channel'];
        $platform = $_REQUEST['platform'];
        $appid = $_REQUEST['appid'];
        $buffer = $_REQUEST['buffer'];

        $data['receipt-data'] = $buffer;
        $jsonStr = json_encode($data);

        //var_dump($jsonStr);
        $resStr = iosvpost("https://buy.itunes.apple.com/verifyReceipt", 30, $jsonStr);
        //$resStr = iosvpost("https://sandbox.itunes.apple.com/verifyReceipt", 30, $jsonStr);
        //$resStr = datapost("https://buy.itunes.apple.com/verifyReceipt", $jsonStr);
        //var_dump($resStr);
        $receipt = json_decode($resStr, true);        
        log_message("request is $_REQUEST and jsonStr is $jsonStr and return is $receipt", "appstorePayment");
        //var_dump($receipt);
        if ($receipt['status'] == 21007) {    //返回21007表示是个沙盒验证
            $resStr = iosvpost("https://sandbox.itunes.apple.com/verifyReceipt", 30, $jsonStr);
            unset($receipt);
            $receipt = json_decode($resStr, true);
            //var_dump($receipt);
        }

		$receipt_time_tmp = substr($receipt['receipt']['purchase_date'], 0, 19);
        $receipt_time_tmp = strtotime($receipt_time_tmp) + 14400;
        $receipt['receipt']['purchase_date'] = date("Y-m-d H:i:s", $receipt_time_tmp);
        $resStr = json_encode($receipt, true);

        $tmplogstr = http_build_query($receipt);
        log_message($tmplogstr, "appstorePayment");

        //exit($resStr);
        //如果验证成功
        $getroleid = $roleid;
        $ret = 4;
        $money = 0;
        $diamond = 0;
        $my_product_id;
        $paytimes = 0;  //第几次支付
        if ($receipt['status'] == 0) {
            $receipt_data = $receipt['receipt'];
            $orderid = $receipt_data['transaction_id'];
            $product_id = $receipt_data['product_id'];
            
            $num = (int) $receipt_data['quantity']; //购买的商品数量
            //print_r($receipt_data);exit;

            $product_row = $this->db->one("SELECT * FROM {pre}appstore_product WHERE product_id='$product_id'"); //获取该商品信息
            if ($product_row !== NULL) {
                $money = $product_row['rmb'] * $num; //数量乘以单笔价值人民币
                $diamond = $product_row['gold'] * $num;
                $my_product_id = $product_row['my_product_id'];
                $ret = 0;
            } else {
                log_message(" product_id error : {$product_id};", "appstorePayment");
                $ret = 5;       //商品ID无效，无效订单
            }

            $purchase_date = $receipt_data['purchase_date'];
            $row = $this->db->one("SELECT * FROM {pre}payment WHERE orderid='$orderid' AND platform='0' AND channel='appstore' AND finish_time='$purchase_date'");
            //新订单
            if ($row === null) {
                $sql = "INSERT INTO {pre}payment(orderid,serverid,roleid,accountid,create_time,status,channel,platform,appid,money,finish_time,product_id) VALUES
                    ('$orderid','$serverid','$roleid','$accountid','$purchase_date',1,'appstore','0','$appid','{$product_row['rmb']}','$purchase_date','$product_id')";
                $res = $this->db->execute($sql);
                if ($res === FALSE) {
                    log_message("{$orderid} orderid insert error;", "appstorePayment");
                    $ret = 2;
                } else {
                    $ret = 0;   //成功
                }
            } else {
                $getroleid = $row['roleid'];    //将订单生产时的角色ID赋值
                $ret = 0;
            }
        }
        //如果验证不成功，写入临时表
        else {
            $ret = 4;       //无效订单
            $now = time();
            $strnow = date("Y-m-d H:i:s", $now);
            $sql = "INSERT INTO {pre}payment_appstore_tmp(orderid,serverid,roleid,accountid,status,channel,platform,appid,create_time,content,last_time,times) VALUES('$orderid','$serverid','$roleid','$accountid',0,'appstore', 1,'$appid','$strnow','$buffer',{$now},1)";
            $this->db->execute($sql);
            if ($res == FALSE) {
                log_message("{$orderid} orderid insert error;", "appstorePayment");
            }
        }
        //第几次充值
        $sql = "SELECT * FROM {pre}payment WHERE serverid = $serverid AND roleid = $roleid";
        $this->db->query($sql);
        $rolepayarr = array();
        while ($n = $this->db->get_array())
        {
        	$rolepayarr[] = $n;
        }
        for ($i = 0; $i < count($rolepayarr); $i++)
        {
        	if (isset($rolepayarr[$i]['money']))
        	{
        		$paytimes += 1;
        	}
        }

        $response = "/aa=1&roleid=$roleid&ret=$ret&getroleid=$getroleid&json_str=$resStr&money=$money&product_id=$my_product_id&diamond=$diamond&paytimes=$paytimes";
        echo $response;
        exit;
    }

    //全局Http服务器请求选区策略
    function AreaStrategy() {
        $sql = "SELECT * FROM {pre}area_strategy LIMIT 1";
        $row = $this->db->one($sql);
        $row['strategy'] = $row['strategy'] . ";" . $row['areas'];

        $this->db->query("SELECT id,state,name,opentime,flag FROM {pre}areasample");
        while ($rowdata = $this->db->get_array()) {
            $rowdata['id'] = (int) $rowdata['id'];
            $rowdata['opentime'] = (int) $rowdata['opentime'];
            $rowdata['state'] = (int) $rowdata['state'];
            $rowdata['flag'] = (int) $rowdata['flag'];
            $rowdata['name'] = (string) $rowdata['name'];
            $arealist[] = $rowdata;
        }

        $row['arealist'] = $arealist;
        echo json_encode($row);
    }

    //获得所有屏蔽的渠道
    function getAllChannel()
    {
    	$tmpconnect = $this->load->database('center_db') or die("load failed!".mysql_error());
    	$sql = "SELECT channelname,status FROM channelmanager";
    	$tmpconnect->query($sql);
    	$tmpstr = "";
    	while($n = $tmpconnect->get_array())
    	{
    		if ($n['channelname'] == 'shzmTest')
    			$n['channelname'] = 'PCChannel';
    		$tmpstr .= $n['channelname'].";".$n['status'].",";
    	}
    	$tmpstr = substr($tmpstr, 0, -1);
    	echo "channelstr=$tmpstr";
    }
    
    //客户端请求获取当前的Logo  dragon.hu add@2016.5.10  http://192.168.18.20/master/mcGM/api/getCurrentLogo
    function getCurrentLogo()
    {
    	$config = get_config();
    	$tmparr = array("currentLogo" => $config['currentLogo']);
    	echo json_encode($tmparr);
    }
    
    function GetLanStr($languageID,$lansel,$strDefaultStr) {
    	if(!isset($languageID))
    		return $strDefaultStr;
    	if($lansel == -1)
    		return $strDefaultStr;
    	#$config = get_config();
    	#var_dump($config['inc']['lansel']);
    	#exit(0);
    	#var_dump($lansel);
    	$this->tmpconnect = $this->load->database('type_db') or die("load failed!".mysql_error());
    	
        $sql = "SELECT * from s_type_language dl where dl.ID = $languageID LIMIT 1;";
        #var_dump($sql);
    	$this->tmpconnect->query($sql);
    	#$row = array();
        while($n = $this->tmpconnect->get_array('default'))
        {
        	$columname = "language_" . $lansel;
        	if( isset( $n[$columname]))
        	{
        		return $n[$columname];
        	}
        	else 
        	{
        		return $strDefaultStr;
        	}
        }
        return $strDefaultStr;
    }
    
    //创建一笔第三方订单
    function createPayRecord() {
        $row = $_GET;
        $row['create_time'] = date("Y-m-d H:i:s", time());
        $row['status'] = 0;
        $res = $this->db->insert("{pre}payment", $row);
        $strResult = "roleid=" . $row['roleid'] . "&orderid=" . $_GET['orderid'];
        if ($res !== FALSE)
            echo $strResult . "&ret=success";
        else {
            echo $strResult . "&ret=fail";
        }
        ///echo $strResult. "&ret=fail";
    }

    
    function writeNoticeInfo($lansel){
    	#log_message("writeNoticeInfo is called! lansel = " . $lansel);
    	$sql = "SELECT * FROM {pre}notice";
    	$this->db->query($sql);
    	
    	$result = array();
    	$tmp_notic_array = array(); 
    	$notic_array = array();
    	
    	$config = get_config();
    	$lanconfig = $config['inc']['lansel'];
    	
    	while($rowdata = $this->db->get_array()){

    		$rowdata['content']=str_replace('"', ' ', $rowdata['content']);
    		
    		//是否显示"新"字,为1表示显示
    		strtotime($rowdata['inserttime']) + $rowdata['timesec'] > time() ? $rowdata['flag'] = 1 : $rowdata['flag'] = 0;
    		
			//查询shouhuzhemen_type数据库,根据$lansel取得对应的多语言
			$language_ID = $rowdata['language_ID'];
			$language_ID1 = $rowdata['language_ID1'];
			$language_ID2 = $rowdata['language_ID2'];
			
			$strLanName = $this->GetLanStr($language_ID,$lansel,$rowdata['name']);
			$strLanTitle = $this->GetLanStr($language_ID1,$lansel,$rowdata['title']);
			$strLanContent = $this->GetLanStr($language_ID2,$lansel,$rowdata['content']);
			
			if ($rowdata['type'] == 1){
				$tmp_notic_array[$rowdata['tmpsequence']] = array(
									'name' => urlencode($strLanName),
									'flag' => urlencode($rowdata['flag']),
									'title' => urlencode($strLanTitle),
									'content' => urlencode($strLanContent)
							);
			}
			else{
				$rowdatalist2 = array(
						'name' => urlencode($strLanName),
						'flag' => urlencode($rowdata['flag']),
						'title' => urlencode($strLanTitle),
						'content' => urlencode($strLanContent)
				);	
			}
    	}
    	#var_dump($tmp_notic_array);
    	#var_dump('2'. $rowdatalist2);
    	//根据key值排序
    	//print_r($tmp_notic_array);
    	//echo "<br>++++<br>";
    	ksort($tmp_notic_array);
    	//print_r($tmp_notic_array);
    	foreach ($tmp_notic_array as $k=>$v){
    		$notic_array[] = $v;
    	}
    	//echo "<br>++++<br>";
    	//print_r($notic_array);
    	//exit(0);
    	
    	$result["close"] = isset($rowdatalist2);
    	if(!$result["close"])
    	{
    		$result["notics"] = $notic_array;
    	}
    	else
    	{
    		$result["notics"] = array();
    		$result["notics"][] = $rowdatalist2;
    	}
    	#echo urldecode(json_encode($result));
        #var_dump($result);
        $URLDE_DATA = urldecode(json_encode($result));
        #echo $URLDE_DATA;
        if(-1 == $lansel)
        {
			$filename = 'notice.html';        	
        }
		else 
		{
			$filename = $lanconfig[$lansel];
			#var_dump($filename);
		}
		
        $myfile = fopen("./tmp_process/" . $filename , "w") or die("Unable to open file!");
        if(false != $myfile)
        {
            fwrite($myfile, $URLDE_DATA);
            fclose($myfile);
        }
    }
    
    
    
    
    //给客户端发送公告内容    http://192.168.18.21/master/mcGM/api/sendNoticeInfo
    function sendNoticeInfo(){
    	$config = get_config();
    	#var_dump($config);
    	#exit(0);
    	$lanconfig = $config['inc']['lansel'];
    	#log_message("sendNoticeInfo" . serialize($lanconfig));
		#var_dump($lanconfig);
		#exit(0);
    	//for循环，将config里面的各种语言解析出，放到数组中，如果是notice.html则置-1
    	$tmpset = 0;
		foreach ($lanconfig as $lank => $lanv )
		{
			$lansel = $lank;
			#log_message("lansel is = " . $lansel . "lanv = " . $lanv);
			#var_dump($lansel);
			#log_message("lansel is = " . $lansel);
			if( 0 == strcmp('notice.html', $lanv))
			{
				#log_message("lansel = -1;");
				$lansel = -1;
				$tmpset++;
			}
			#log_message("lansel is = " . $lansel . ",lanv = " . $lanv . ",tmpset = " . $tmpset);
			if( (-1 == $lansel && $tmpset <= 1) || (-1 != $lansel) )
			{
				$this->writeNoticeInfo($lansel);	
			}
		}
		#exit(0);
    }

    /****************************************dragon.hu 2015.6.13 add 数值数据采集部分********************************************/
	//角色副本相关的统计信息的保存
    function roleFBInfo()
    {
    	$row = $_GET;
    	//有就更新，没有就创建
    	$roleid = $row['roleid'];
    	$serverid = $row['serverid'];
    	$fbtype = $row['fbtype'];
    	$fbid = $row['fbid'];
    	
    	$paymentDb = $this->load->database('payment_db');
    	//echo "select * from tt_playerfbdata where roleid = '$roleid' and serverid = '$serverid'<br>";
    	$sql = "select * from tt_playerfbdata where roleid = '$roleid' and serverid = '$serverid' and
    			fbtype = '$fbtype' and fbid = '$fbid'";
    	$paymentDb->query($sql);
    	$n = $paymentDb->get_array('default');
    	//累加次数
    	$row['onenter_amounts'] += $n['onenter_amounts'];
    	$row['die_amounts'] += $n['die_amounts'];
    	$row['finish_amounts'] += $n['finish_amounts'];
    	$row['total_time'] += $n['total_time'];
    	
    	$one = $paymentDb->one($sql);
    	//print_r(count($one));
    	//exit(0);
    	if (count($one) >= 1){
    		$paymentDb->update("tt_playerfbdata", $row, array('roleid' => $roleid, 'serverid' => $serverid, 'fbtype' => $fbtype, 
    		'fbid' => $fbid
    		));
    	}else{
    		$paymentDb->insert("tt_playerfbdata", $row);
    	}
    }
    
    //角色货币及其他相关信息的统计（角色相关的就不用了，有LOG统计）
    function roleMoneyLog()
    {
    	$row = $_GET;
    	$roleid = $row['roleid'];
    	$serverid = $row['serverid'];
    	
    	$paymentDb = $this->load->database('payment_db');
    	
    	$sql = "select * from tt_playerroledata where roleid = '$roleid' and serverid = '$serverid'";
    	$paymentDb->query($sql);
    	$n = $paymentDb->get_array('default');
    	//累加次数
    	$row['gang_rich_add'] += $n['gang_rich_add'];
    	$row['gold_add'] += $n['gold_add'];
    	$row['diamond_add'] += $n['diamond_add'];
    	$row['prestige_add'] += $n['prestige_add'];
    	$row['glory_add'] += $n['glory_add'];
    	$row['smelt_add'] += $n['smelt_add'];
    	$row['exp_add'] += $n['exp_add'];
    	$row['gang_exp_add'] += $n['gang_exp_add'];
    	
    	$one = $paymentDb->one($sql);
    	
    	if (count($one) >= 1)
    	{
    		$paymentDb->update("tt_playerroledata", $row, array('roleid' => $roleid, 'serverid' => $serverid));
    	}else{
    		$paymentDb->insert("tt_playerroledata", $row);
    	}
    }
    
    //服务器金币数据分析(完成)
    function serverGoldAnalysis()
    {
    	$row = $_GET;
    	$serverid = $row['serverid'];
    	$time = time();
    	$date = date("y-m-d", $time); //获取当前日期
    	$paymentDb = $this->load->database('payment_db');
    	$sql = "SELECT * FROM tt_servergolddata WHERE serverid = '$serverid' AND cur_date = '$date'";
    	$paymentDb->query($sql);
    	$n = $paymentDb->get_array('default');
    	$row['cur_amounts'] += $n['cur_amounts'];
    	$row['add_amounts'] += $n['add_amounts'];
    	$row['expend_amounts'] += $n['expend_amounts'];
    	
    	$one = $paymentDb->one($sql);
    	if (count($one) >= 1)
    	{
    		$paymentDb->update("tt_servergolddata", $row, array('serverid' => $serverid, 'cur_date' => $date));
    	}else{
    		$paymentDb->insert("tt_servergolddata", $row);
    	}
    	
    }
    
    //服务器其他数据分析(完成)
    function serverOtherAnalysis()
    {
    	$row = $_GET;
    	$serverid = $row['serverid'];
    	$time = time();
    	$date = date("y-m-d", $time);
    	
    	$paymentDb = $this->load->database('payment_db');
    	
    	$sql = "select * from tt_serverstatistics where serverid = '$serverid' and cur_date = '$date'";
    	$paymentDb->query($sql);
    	$n = $paymentDb->get_array('default');
    	//累加次数
    	//金币消耗和产量信息待定。。。
    	$row['addEquipNum'] += $n['addEquipNum'];
    	$row['addOrangeEquipNum'] += $n['addOrangeEquipNum'];
    	$row['expendOrangeEquipNum'] += $n['expendOrangeEquipNum'];
    	$row['AddThreeStarPet'] += $n['AddThreeStarPet'];
    	$row['addOrangeGemNum'] += $n['addOrangeGemNum'];
    	$row['addRedGemNum'] += $n['addRedGemNum'];
    	$row['smeltNum'] += $n['smeltNum'];
    	
    	$one = $paymentDb->one($sql);
    	
    	if (count($one) >= 1)
    	{
    		$paymentDb->update("tt_serverstatistics", $row, array('serverid' => $serverid, 'cur_date' => $date));
    	}else{
    		$paymentDb->insert("tt_serverstatistics", $row);
    	}
    }
    
    //服务器熔炼总量
    function serverSmeltLog()
    {
    	$row = $_GET;
    	//print_r($row);
    	//exit(0);
    	$serverid = $row['serverid'];
    	 
    	$paymentDb = $this->load->database('payment_db');

    	$sql = "select * from tt_serversmeltdata where serverid = '$serverid'";
    	
    	$paymentDb->query($sql);
    	//累加次数
    	$n = $paymentDb->get_array('default');
    	$row['blue_equip_smelt'] += $n['blue_equip_smelt'];
    	$row['purple_equip_smelt'] += $n['purple_equip_smelt'];
    	$row['pink_equip_smelt'] += $n['pink_equip_smelt'];
    	$row['orange_equip_smelt'] += $n['orange_equip_smelt'];
    	
    	$one = $paymentDb->one($sql);
    	 
    	if (count($one) >= 1)
    	{
    		$paymentDb->update("tt_serversmeltdata", $row, array('serverid' => $serverid));
    	}else{
    		$paymentDb->insert("tt_serversmeltdata", $row);
    	}
    }
    
    //服务器装备产出总量
    function serverEquipLog()
    {
    	$row = $_GET;
    	//print_r($row);
    	//exit(0);
    	$serverid = $row['serverid'];
    	 
    	$paymentDb = $this->load->database('payment_db');
    	 
    	$sql = "select * from tt_serverequipdata where serverid = '$serverid'";
    	
    	$paymentDb->query($sql);
    	//累加次数
    	$n = $paymentDb->get_array('default');
    	$row['blue_equip'] += $n['blue_equip'];
    	$row['purple_equip'] += $n['purple_equip'];
    	$row['pink_equip'] += $n['pink_equip'];
    	$row['orange_equip'] += $n['orange_equip'];
    	
    	$one = $paymentDb->one($sql);
    	 
    	if (count($one) >= 1)
    	{
    		$paymentDb->update("tt_serverequipdata", $row, array('serverid' => $serverid));
    	}else{
    		$paymentDb->insert("tt_serverequipdata", $row);
    	}
    }
    /****************************************************************************************************/
    /*1、激活LOG						
     * dragon.hu add @2015.8.14 activateLog
     * 用户下载客户端第一次点击游戏icon时即为激活，LOG类型编号、时间、机型、设备码、手机MEI、手机MAC	
     * http://192.168.1.18/master/mcGM/api/activateLog?device_type=test&device_id=test&device_mei=test&device_mac=test
     */
    function activateLog()
    {
    	$row = $_GET;

    	$this->log("activateLog", $row);
    	$tmpConn = $this->load->database('log_db');
    	//print_r($row);
    	//exit(0);
    	
        $one = $tmpConn->one("SELECT * FROM deviceactivation WHERE device_id='{$row[device_id]}'");
        if (count($one) >= 1)
        {
            $tmpBool = false;
           	$this->log("activateLog", $row);
            //print_r($row);
            //exit(0);
            
            for ($x=1; $x<=$this->logParamVal; $x++)
            {
                $tmpParam = 'param' . $x;
                if(true == array_key_exists($tmpParam, $row))
                {
                    $one[$tmpParam] = $row[$tmpParam];
                    $tmpBool = true;
                }
            } 
            if(null == $one['installtime'])
            {
                $one['installtime'] = 0;
            }
            
            if(false == $tmpBool)
            {
                return ;
            }
            
            $res = $tmpConn->update("deviceactivation", $one, array('device_id' => $row[device_id]));
        }
        else
        {
            $row['logtype'] = 1;    //激活log类型都置为1
            $row['inserttime'] = date("Y-m-d H:i:s", time());
            $res = $tmpConn->insert("deviceactivation", $row);
        }
    	if ($res == FALSE) {
    		$this->log("activateLog", "activateLog info insert into activatedevice fail !!! row=".$row);
    		log_message("activateLog info insert into activatedevice fail !!!");
    		echo "fail";
    	} else {
    		echo "success";
    	}
    }
    
    /// 客户端在开机时对资源的处理
    /// http://192.168.18.23/master/mcGM/api/activateSrcLog?device_id=PCDeviceID&param5=actionname-UpdateCheckEnd+param1-NoUpdate
    function activateSrcLog()
    {
    	$row = $_GET;
        $tmpConn = $this->load->database('log_db');
        $one = $tmpConn->one("SELECT * FROM deviceactivation WHERE device_id='{$row[device_id]}'");

        if (count($one) >= 1)
        {
           	$this->log("activateLog", $one);
            $tmpBool = false;
            for ($x=1; $x<=$this->logParamVal; $x++)
            {
                $tmpParam = 'param' . $x;
                if(true == array_key_exists($tmpParam, $row))
                {
                    $one[$tmpParam] = $row[$tmpParam];
                    $tmpBool = true;
                }
            } 
            if(null == $one['installtime'])
            {
                $one['installtime'] = 0;
            }
            
            if(false == $tmpBool)
            {
                return ;
            }
            #var_dump($one['installtime']);
            #print_r($one);
            #exit(0);

            $res = $tmpConn->update("deviceactivation", $one, array('device_id' => $one[device_id]));
        }
        else
        {
            $row['logtype'] = 1;    //激活log类型都置为1
            $row['inserttime'] = date("Y-m-d H:i:s", time());
            $res = $tmpConn->insert("deviceactivation", $row);
        }
    	if ($res == FALSE) {
    		$this->log("activateLog", "activateLog info insert into activatedevice fail !!! row=".$row);
    		log_message("activateLog info insert into activatedevice fail !!!");
    		echo "fail";
    	} else {
    		echo "success";
    	}
    }
    
    //appsfly的数据备份    http://***.***.***.***/master/mcGM/api/AppsflyData
    function AppsflyData()
    {
    	//接收数据
    	$request = file_get_contents("php://input");
    	$this->log("AppsflyData", $request);
    	
    	$row = json_decode($request,true);
    	$tmpConn = $this->load->database('log_db');
    	
    	//存表
    	if ($row['platform'] == 'ios')
    	{
    		//存ios表  AppsflyDataIOS
    		$res = $tmpConn->insert("AppsflyDataIOS", $row);
    		if ($res == FALSE) {
    			$this->log("AppsflyData", "AppsflyData ios info insert into AppsflyDataIOS fail !!! row=".$row);
    			log_message("AppsflyData ios info insert into AppsflyDataIOS fail !!!");
    			echo "fail";
    		} else {
    			echo "success";
    		}
    	}
    	elseif ($row['platform'] == 'android')
    	{
    		//存android表  AppsflyDataAndroid
    		$res = $tmpConn->insert("AppsflyDataAndroid", $row);
    		if ($res == FALSE) {
    			$this->log("AppsflyData", "AppsflyData Android info insert into AppsflyDataAndroid fail !!! row=".$row);
    			log_message("AppsflyData Android info insert into AppsflyDataAndroid fail !!!");
    			echo "fail";
    		} else {
    			echo "success";
    		}
    	}
    }
    
    function log($folderName, $data) {
    	if (is_array($data)) {
    		$log = date("Y-m-d H:i:s") . " " . http_build_query($data) . "\r\n";
    		//$log = date("Y-m-d H:i:s") . " device_type=" . $data['device_type']." device_id=". $data['device_id']." device_mei=". 
    		//$data['device_mei']." device_mac=".$data['device_mac']." installtime=".$data['installtime']. "\r\n";
    	} else {
    		$log = date("Y-m-d H:i:s") . " " . $data . "\r\n";
    	}
    	$path = APPPATH . "tmplog/{$folderName}/";
    	createDir($path);
    	$path = $path . date("Y-m-d") . ".txt";
    	file_put_contents($path, $log, FILE_APPEND);
    }
    /****************************************************************************************************/
    /*
     *1. 记录提问内容       这个功能不需要了！！！！！
     * dragon.hu add @2015.8.21  tt_gmhelper
     * http://192.168.1.18/master/mcGM/api/recordQuestionData?roleid=123&askcontent=test&serverid=18&asktime=1440385140&questionstate=0
     */
    function recordQuestionData()
    {
    	$row = $_GET;
    	//print_r($row);
    	//exit(0);
    	//插入表tt_gmhelper中,小于10分钟的提问则覆盖
    	$sql = "SELECT * FROM tt_gmhelper";
    	$this->db->query($sql);
    	$tmprow = array();
    	while($n = $this->db->get_array('default'))
    	{
    		$tmprow[] = $n;
    	}
    	foreach ($tmprow as $k=>$v)
    	{
    		$tmptime = strtotime($v['asktime']);
    		//print_r($row['asktime']);
    		//echo "++++";
    		//print_r($tmptime);
    		//echo "++++";
    		$diftime = $row['asktime'] - $tmptime;
    		//print_r($diftime);
    		//exit(0);
    		if ($v['serverid'] == $row['serverid'] && $v['roleid'] == $row['roleid'] && $diftime < 60*10)//同一个玩家10分钟之内不能发多与一条
    		{
    			$sql = "delete from tt_gmhelper where serverid = {$v['serverid']} and roleid = {$v['roleid']} and asktime ="."'".$v['asktime']."'";
    			$this->db->execute($sql);
    			break;
    		}
    	}
    	$row['asktime'] = date("Y-m-d H:i:s", $row['asktime']);
    	$res = $this->db->insert("tt_gmhelper", $row);
    	$strResult = "roleid=" . $row['roleid'];
    	if ($res !== FALSE)
    	{
    		echo $strResult . "&ret=success";
    	}
    	else
    	{
    		echo $strResult . "&ret=fail";
    	}
    }
    /****************************************************************************************************/
    /*
     * 由益玩发过来的问题和解答，需要转发给游戏服
     * dragon.hu add @2015.9.7
     * 发过来的格式为：http://121.40.207.78/master/mcGM/api/receiveQuestion?qid=76&userid=u123456&serverid=s1&t=1441594953&s=4906348289d34d0f6d6e8f0bc7958580;
     */
    function receiveQuestion()
    {
    	$signkey = "TLvabkuTc2a5xFzX";  //益玩给的signkey这个不变不能修改
    	//接收数据
    	$row = $_GET;
    	//print_r($row);
    	//exit(0);
    	//md5验证
    	$tmpstr = $row['qid'].$row['userid'].$row['serverid'].$row['roleid'].$row['t'].$signkey;//userid就是openid
    	$tmpS = md5($tmpstr);
    	if ($tmpS == $row['s'])
    	{
    		//发送
    		$arealist = get_area_list_url();
    		//print_r($arealist);
    		//echo "<br>++++<br>";
    		//print_r($arealist[$row['serverid']] . array_to_stringparam($row)."action=54");
    		//exit(0);
    		$strResult = vpost($arealist[$row['serverid']] . array_to_stringparam($row)."action=54");
    		//if($strResult){}  //不管结果如何
    		//返回值为(为方便调试，游戏方接收到请求后，需返回字符串succ)
    		echo "succ";
    	}else{
    		echo "fail";
    	}
    }

    /**
     * 激活码验证接口
     * 发过来的格式为：http://121.40.207.78/master/mcGM/api/cdKey?keyChar=76&roleId=u123456&serverId=s1&sign=4906348289d34d0f6d6e8f0bc7958580;
     */
    function  cdKey()
    {
        $signkey = md5('key');  //益玩给的signkey这个不变不能修改
        //接收数据
        //$row = json_decode($GLOBALS['HTTP_RAW_POST_DATA'],true);
        $content=file_get_contents('php://input');
        $row = json_decode(file_get_contents('php://input'),true);
        //md5验证
        $tmpstr = $row['keyChar'].$row['roleId'].$row['serverId'].$signkey;//userid就是openid
        $tmpS = md5($tmpstr);
        if ($tmpS == $row['sign'])
        {
            //连中心服务器
            $this->center_connect = $this->load->database('db');
            //$sql = "SELECT * FROM cdkey WHERE keyChar ='".$row['keyChar']."'"."and now() between STR_TO_DATE(starttime,'%Y-%m-%d %H:%i:%s') and STR_TO_DATE(endtime,'%Y-%m-%d %H:%i:%s')";
            $sql = "SELECT * FROM cdkey WHERE keyChar ='".$row['keyChar']."'";
            $this->center_connect->query($sql);
            $code1=$this->center_connect->get_array();
            //var_dump($code1);
            if($code1 == null){
                $data['status']['code']=1;
                $data['status']['message']=(string)'not exist';
                echo json_encode($data);
                return;
            }

            // 同一类型的礼包只能领取一次
            $sql2 = "SELECT * FROM cdkey WHERE roleid ='".$row['roleId']."'"."and rewardobjectid = '".$code1['rewardobjectid']."'";
            $this->center_connect->query($sql2);
            $code2=$this->center_connect->get_array();
            if($code2 != null){
                $data['status']['code']=8;
                //$data['status']['message']=(string)'same type code already get';
                $data['status']['message']=$sql2;
                echo json_encode($data);
                return;
            }

            date_default_timezone_set("PRC");
            $starttime = strtotime($code1['starttime']);
            $endtime = strtotime($code1['endtime']);
            $nowtime = time();
            if ($starttime > $nowtime ) {
                $data['status']['code']=2;
                $data['status']['message']=(string)'wait time';
                echo json_encode($data);
                return;
            } else if ($endtime < $nowtime) {
                $data['status']['code']=3;
                $data['status']['message']=(string)'time out';
                echo json_encode($data);
                return;
            }

            if ($row['viplevel'] < $code1['viplevel']) {
                $data['status']['code']=4;
                $data['status']['message']=(string)'VIP too low';
                echo json_encode($data);
                return;
            }

            if ($code1['isuse'] == 2) { // 激活码已被使用
                $data['status']['code']=5 ;
                $data['status']['message']=(string)'used code';
                echo json_encode($data);
                return;
            }

            //if ($code1['channel'] != "" && $code1['channel'] != $row['channel']) {
            if ($code1['channel'] != "全渠道" && $code1['channel'] != $row['channel']) {
                $data['status']['code']=6 ;
                //$data['status']['message']=(string)'channel missmatch';
                $data['status']['message']= strval($code1['channel']) . " + " . $row['channel'];
                echo json_encode($data);
                return;
            }

            //设置激活码状态为 已使用 2
            $sql = "update cdkey set `areaid` = '$row[serverId]',`roleid`='$row[roleId]' ,`isuse`=2 where id = $code1[id]";
            if (false == $this->center_connect->execute($sql)) {
                $data['status']['code']=7;
                $data['status']['message']=(string)"system err";
                echo json_encode($data);
                return;
            }

            // 根据激活码 礼包ID 得到实际物品信息
            $sql = "SELECT * FROM dynamic_giftbagdetail WHERE giftbagid='".$code1['rewardobjectid']."'";
            $this->center_connect->query($sql);
            $code2=$this->center_connect->row();

            $object=array();
            $data['status']['code']=(int)0;
            $data['status']['message']=(string)'success';
            $data['data']['roleId']=(int)$row['roleId'];
            $data['data']['serverId']=(int)$row['serverId'];
            $data['data']['giftbagid']=(int)$code1['rewardobjectid'];
            foreach ($code2 as $k=>$v){
                $object[$k]['objectid']=(int)$v['objectid'];
                $object[$k]['count']=(int)$v['mincount'];
            }

            $data['data']['object']=$object;
            
            echo json_encode($data);
        }else{
            $data['status']['code']=7;
            $data['status']['message']=(string)'sign error';
            echo json_encode($data);
        }
    }
    
}
